package com.ruoyi.system.controller;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.QTelManyi;
import com.ruoyi.system.service.IQTelManyiService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.nio.file.*;
import java.io.*;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.Control.Customer;
import com.ruoyi.system.Control.ExcelMergeCellHandler;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.QPingjia;
import com.ruoyi.system.service.IQPingjiaService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 呼叫满意度Controller
 *
 * @author ruoyi
 * @date 2024-06-21
 */
@Controller
@RequestMapping("/system/manyi")
public class QTelManyiController extends BaseController {
    private String prefix = "system/manyi";

    static List<QTelManyi> listExcel = new ArrayList<QTelManyi>();

    @Autowired
    private IQTelManyiService qTelManyiService;

    @RequiresPermissions("system:manyi:view")
    @GetMapping()
    public String manyi() {
        return prefix + "/manyi";
    }

    @GetMapping("/poplist")
    public String poplist(@RequestParam("agentid") String agentid, @RequestParam("startTime") String startTime,   @RequestParam("endTime") String endTime, ModelMap mmap) {
        mmap.put("agentid",agentid);
        mmap.put("startTime",startTime);
        mmap.put("endTime",endTime);
        System.out.println("=================================================startTime:"+startTime);
        return prefix + "/poplist";
    }

    public String getSUMjts(List<QTelManyi> list) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            sum += Integer.valueOf(list.get(i).getHrjtzs());
        }
        return sum + "";
    }

    public String getSUMmys(List<QTelManyi> list) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            sum += Integer.valueOf(list.get(i).getManyi() == null ? "0" : list.get(i).getManyi());
        }
        return sum + "";
    }

    public String getSUMyiban(List<QTelManyi> list) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            sum += Integer.valueOf(list.get(i).getYiban());
        }
        return sum + "";
    }

    public String getSUMnomanyi(List<QTelManyi> list) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            sum += Integer.valueOf(list.get(i).getNomanyi());
        }
        return sum + "";
    }

    /**
     * 查询呼叫满意度列表
     */
   // @RequiresPermissions("system:manyi:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(QTelManyi qTelManyi) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        startPage();
        List<QTelManyi> list = qTelManyiService.selectQTelManyiList(qTelManyi);

        List<QTelManyi> listRes = new ArrayList<QTelManyi>();

        for (QTelManyi test : list) {
            QTelManyi tmp = new QTelManyi();
            PropertyUtils.copyProperties(tmp, test);
            BigDecimal csl = new BigDecimal(test.getCsl() != null ? test.getCsl() : "0");
            BigDecimal roundedValue = csl.setScale(2, RoundingMode.HALF_UP);
            BigDecimal manyilv = new BigDecimal(test.getManyilv() != null ? test.getManyilv() : "0");
            BigDecimal roundedValuemylv = manyilv.setScale(2, RoundingMode.HALF_UP);
            tmp.setCsl(String.valueOf(roundedValue) + '%');
            tmp.setManyilv(String.valueOf(roundedValuemylv) + '%');
            listRes.add(tmp);
        }

        QTelManyi zongji = new QTelManyi();
        zongji.setMydName("总计");
        zongji.setHrjtzs(getSUMjts(list));
        zongji.setManyi(getSUMmys(list));
        zongji.setYiban(getSUMyiban(list));
        zongji.setNomanyi(getSUMnomanyi(list));

        float sum = Float.valueOf(getSUMjts(list));
        float yiban = Float.valueOf(getSUMyiban(list));
        float nomanyi = Float.valueOf(getSUMnomanyi(list));
        float manyi = sum - yiban - nomanyi;
        float manyilv = (manyi / sum) * 100;
        double number = manyilv;
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        String result = decimalFormat.format(number);
        System.out.println(result);
        System.out.println(manyilv + "================================");
        zongji.setManyilv(String.valueOf(result) + '%');
        listRes.add(zongji);
        this.listExcel = listRes;
        return getDataTable(listRes);
    }

    /**
     * 导出呼叫满意度列表
     */
    @RequiresPermissions("system:manyi:export")
    @Log(title = "呼叫满意度", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(QTelManyi qTelManyi) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        List<QTelManyi> data = qTelManyiService.selectQTelManyiList(qTelManyi);

        List<QTelManyi> listRes = new ArrayList<QTelManyi>();

        listRes = this.listExcel;


        String filename = new String("满意度报表(tmplate)" + ".xlsx");


        Path sourcePath = Paths.get(getAbsoluteFile(filename));
        Path destinationPath = Paths.get(getAbsoluteFile("满意度统计.xlsx"));


        try {
            Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File copied successfully.");
        } catch (IOException e) {
            System.out.println("Error occurred while copying file.");
            e.printStackTrace();
        }


        try {
            FileInputStream file = new FileInputStream(getAbsoluteFile("满意度统计.xlsx"));
            Workbook workbook = WorkbookFactory.create(file);
            Sheet sheet = workbook.getSheetAt(0);
            int rowIndex = 3;  //从第三行开始写
            for (int i = 0; i < listRes.size(); i++) {
                QTelManyi tmp = new QTelManyi();
                tmp = (QTelManyi) listRes.get(i);


                Row row = sheet.getRow(i + rowIndex);
                int colIndex = 0;
                Cell cell = row.getCell(colIndex++);
                cell.setCellValue(tmp.getMydName());

                cell = row.getCell(colIndex++);
                cell.setCellValue(tmp.getHrjtzs());   //接通总数

                cell = row.getCell(colIndex++);
                cell.setCellValue(tmp.getManyi());   //满意

                cell = row.getCell(colIndex++);
                cell.setCellValue(tmp.getYiban());   //一般

                cell = row.getCell(colIndex++);
                cell.setCellValue(tmp.getNomanyi());   //不满意

                cell = row.getCell(colIndex++);
                cell.setCellValue(tmp.getManyilv());   //满意度


            }
            Row row = sheet.getRow(1);
            Cell cell = row.getCell(3);
            // 修改单元格的内容
            cell.setCellValue("统计结束时间：" + qTelManyi.getEndTime());

            row = sheet.getRow(1);
            cell = row.getCell(0);
            // 修改单元格的内容
            cell.setCellValue("统计开始时间：" + qTelManyi.getStartTime());

            file.close();

            FileOutputStream outFile = new FileOutputStream(getAbsoluteFile("满意度统计.xlsx"));
            workbook.write(outFile);
            outFile.close();

            System.out.println("Excel file modified successfully.");

        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.success("满意度统计.xlsx");
    }

    private String getAbsoluteFile(String filename) {
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    /**
     * 新增呼叫满意度
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存呼叫满意度
     */
    @RequiresPermissions("system:manyi:add")
    @Log(title = "呼叫满意度", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(QTelManyi qTelManyi) {
        return toAjax(qTelManyiService.insertQTelManyi(qTelManyi));
    }

    /**
     * 修改呼叫满意度
     */
    @RequiresPermissions("system:manyi:edit")
    @GetMapping("/edit/{mydName}")
    public String edit(@PathVariable("mydName") String mydName, ModelMap mmap) {
        QTelManyi qTelManyi = qTelManyiService.selectQTelManyiByMydName(mydName);
        mmap.put("qTelManyi", qTelManyi);
        return prefix + "/edit";
    }

    /**
     * 修改保存呼叫满意度
     */
    @RequiresPermissions("system:manyi:edit")
    @Log(title = "呼叫满意度", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(QTelManyi qTelManyi) {
        return toAjax(qTelManyiService.updateQTelManyi(qTelManyi));
    }

    /**
     * 删除呼叫满意度
     */
    @RequiresPermissions("system:manyi:remove")
    @Log(title = "呼叫满意度", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(qTelManyiService.deleteQTelManyiByMydNames(ids));
    }
}
